<script setup lang='ts' name="order-recoerd">
import type { IMemeberDetailRes, IOrderDetailRes, IOrderRecordRes, IOrderRecordRow } from '@fl/api/anjutong'
import type { VxeGridInstance, VxeGridListeners } from 'vxe-table'

import EditTag from '@/pages/member/member-public/edit-tag.vue'
import menberAssets from '@/pages/member/member-public/member-assets.vue'
import { MemberDeleteCoupon, MemberTagPage, getMemberDetail, getOrderDetail, getOrderPage, memberContractList, memberCouponList, memberGrowthList, memberPointsList, memberSelect } from '@fl/api/anjutong'
import { ElCard } from 'element-plus'
import { computed, getCurrentInstance, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import type { IAssets } from './types'

import basicData from './component/basic-data/index.vue'
import orderInfo from './component/order-info/index.vue'
import tabsItem from './component/tabs-item/index.vue'
import { useBasicData } from './hooks/use-basic-data'
import { useTable } from './hooks/use-table'

const route = useRoute()
const router = useRouter()

const activeTab = ref(0)
const show = ref<boolean>(false)

const tabs: string[] = ['订单记录', '积分记录', '成长值记录', '优惠劵', '合同']

const instance = getCurrentInstance()
const { column, gridOptions } = useTable(instance)
const { columns, rules, schema } = useBasicData()
const memberTagList = ref()
const tableDataTag = ref({})
const centerDialogVisible = ref(false)
// 会员id 查询页带入
const memberId = ref<number>()
const loading = ref(false)
const form = ref<any>({})
let memberAssets = reactive<any>({ // 定义对象ts
    gradeValue: '白金',
    growthValue: 400,
    sunValue: 4000,
})

const tableInfo = reactive<any>({})
const pageInfo = reactive<{
    page: number
    size: number
}>({
    page: 1,
    size: 10,
})
const getGridOpt = computed(() => {
    return {
        ...gridOptions,
        columns: column[activeTab.value],
        data: tableInfo.data,
        loading: loading.value,
        pagerConfig: {
            currentPage: pageInfo.page,
            pageSize: pageInfo.size,
            total: tableInfo.total,
        },
    }
})

const xGrid = ref<VxeGridInstance<any>>()

const gridEvents: VxeGridListeners<any> = {
    pageChange({ currentPage, pageSize }) {
        pageInfo.page = currentPage
        pageInfo.size = pageSize
        tabChange(activeTab.value, pageInfo)
    },
}

function getData() {
    loading.value = true
    getOrderPage({
        memberId: memberId.value,
        ...pageInfo,
    }).then((res: IOrderRecordRes) => {
        const { records = [], total = 0 } = res
        tableInfo.data = records
        tableInfo.total = total
    }).finally(() => {
        loading.value = false
    })
}

const detail = ref<any>()
function view(row: IOrderRecordRow) {
    show.value = true
    getOrderDetail(row.orderNo as string).then((res: IOrderDetailRes) => {
        detail.value = res
    })
}
function viewFour(row: IOrderRecordRow) {
    console.log(row, '查看合同')
}
function deleteCoupon(row: IOrderRecordRow) {
    console.log(row, '删除优惠券')
    MemberDeleteCoupon({ memberCouponId: row.memberCouponId as string }).then((res) => {
        console.log(res, '删除了吗')
        if (res === true) {
            ElMessage({
                message: '删除成功',
                type: 'success',
            })
        }
        else {
            ElMessage.error('删除失败')
        }
    })
}

async function tabChange(index: number, pages?: any) {
    loading.value = true
    activeTab.value = index

    // 重置page
    pageInfo.page = pages?.page ?? 1
    pageInfo.size = pages?.size ?? 10

    let res: any
    switch (activeTab.value) {
        case 1: // 积分管理
            res = await memberPointsList(memberId.value, { ...pageInfo })
            break
        case 2: // 成长值记录
            res = await memberGrowthList(memberId.value, { ...pageInfo })
            break
        case 3: // 优惠券
            res = await memberCouponList(memberId.value, { ...pageInfo })
            break
        case 4: // 合同
            res = await memberContractList(memberId.value, { ...pageInfo })
            break
        default:
            res = await getOrderPage({
                memberId: memberId.value,
                ...pageInfo,
            })
            break
    }
    const { records = [], total = 0 } = res
    tableInfo.data = records
    tableInfo.total = total
    loading.value = false
}

function getBasicData(memberId: number) {
    getMemberDetail(memberId).then((res: IMemeberDetailRes) => {
        const { memberAssetsVO, memberBaseVO } = res
        form.value = {
            ...memberBaseVO,
        }
        memberAssets = memberAssetsVO as IAssets
    })
}

function doConfirm() {
    init()
}
async function getMemberTagPage() {
    const options = {
        mainCat: '',
        mainCats: ['基础属性', '行为属性', '偏好属性'],
        page: 1,
        size: 10,
        sort: '',
        subCat: '',
        tagName: '',
        type: '1',
    }
    const data = await MemberTagPage(options)
    tableDataTag.value = data
    console.log(tableDataTag.value, 'MemberTagPageMemberTagPage')
}

function goToList() {
    router.go(-1)
}

function init() {
    const id: any = route.query?.id
    if (id) {
        memberId.value = id
        getBasicData(id)
        getMemberSelect(id)
        getMemberTagPage()
        getData()
    }
    else {
        ElMessage.warning('请从会员列表进去详情')
        router.replace('/member-center/member/member-list')
    }
}
async function getMemberSelect(id) {
    try {
        const data = await memberSelect(id)
        memberTagList.value = data
    }
    catch (error) {

    }
}
init()
function editTagSubmit() {
    centerDialogVisible.value = false
    getMemberSelect(memberId.value)
}
</script>

<template>
    <div class="el-card is-always-shadow mb-20 bg-#fff p-30">
        <ElRow>
            <ElButton @click="goToList">
                返回列表
            </ElButton>
        </ElRow>

        <basicData :columns="columns"
                   :form="form"
                   :rules="rules"
                   :schema="schema"
                   @confirm="doConfirm"
        />
    </div>

    <ElCard>
        <div font-700>
            会员标签
            <span ml-20
                  style="cursor: pointer;"
                  color="blue"
                  @click="centerDialogVisible = true"
            >编辑标签
            </span>
        </div>

        <div class="mt-20 flex flex-wrap gap-2">
            <div v-for="(item, index) in memberTagList"
                 :key="index"
            >
                <el-button type="primary"
                           size="small"
                >
                    {{ item?.name }}
                </el-button>
            </div>
        </div>
    </ElCard>

    <menber-assets :member-assets="memberAssets"
                   @refresh="init"
    />

    <div class="el-card is-always-shadow bg-#fff p-30">
        <tabsItem :data="tabs"
                  @handle-click="tabChange"
        >
            <!-- 列表 -->
            <vxe-grid ref="xGrid"
                      v-bind="getGridOpt"
                      v-on="gridEvents"
            >
                <template #textColor="{ row }">
                    <div style="color:#73d13d">
                        {{ row.pointsValue ?? row.parValue ?? row.contractAmount }}
                    </div>
                </template>

                <template #useStatus="{ row }">
                    <div style="color:#f2b245">
                        {{ row.useStatus ?? '' }}
                    </div>
                </template>

                <template #operate="{ row }">
                    <div v-if="activeTab === 0"
                         class="view_btn"
                         @click="view(row)"
                    >
                        查看详情
                    </div>

                    <el-popconfirm title="确认删除吗？"
                                   @confirm="deleteCoupon(row)"
                    >
                        <template #reference>
                            <div v-if="activeTab === 3"
                                 class="view_btn"
                            >
                                删除
                            </div>
                        </template>
                    </el-popconfirm>

                    <div v-if="activeTab === 4"
                         class="view_btn"
                         @click="viewFour(row)"
                    >
                        查看
                    </div>
                </template>
            </vxe-grid>
        </tabsItem>
    </div>
    <!-- 订单详情 -->
    <orderInfo v-model="show"
               :data="detail"
    />

    <el-dialog v-model="centerDialogVisible"
               width="80%"
               title="编辑标签"
               destroy-on-close
    >
        <EditTag :id="memberId"
                 @close="centerDialogVisible = false"
                 @submit="editTagSubmit"
        />
    </el-dialog>
</template>

<style lang="scss" scoped>
.view_btn {
    color: rgb(22 132 252);
    cursor: pointer;
}
</style>
